﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MassOperations.vs2008.Model;
using MassOperations.vs2008.Properties;
using MassOperations.vs2008.Reader;
using System.IO;
using MassOperations.vs2008.View;

namespace MassOperations.vs2008
{
	public partial class FormMain : Form
	{
		private IEnumerable<IStorageReader> _readers;

		public FormMain()
		{
			InitializeComponent();
			try
			{
				DirectoryInfo di = new DirectoryInfo(Settings.Default.source);

				_readers = new List<IStorageReader>();
				foreach (var fi in di.GetFiles("*.csv").Union(di.GetFiles("*.txt")).Union(di.GetFiles("*.xml")).OrderBy(fi => fi.Name))
				{
					switch (fi.Extension.ToLower())
					{
						case ".xml": (_readers as List<IStorageReader>).Add(
						   new XmlStorageReader(fi.FullName)); break;
						case ".csv": case ".txt": (_readers as List<IStorageReader>).Add(
						   new CSVStorageReader(fi.FullName, Settings.Default.separator)); break;
						default:
							continue;
					}
				}

				int offset = 0;
				foreach (var reader in _readers)
				{
					var list = new CustomCheckedListBox
					           	{
					           		Width = Settings.Default.listwidth,
					           		Height = panel.Height,
					           		Left = offset,
					           		Label = {Text = reader.ToString()},
					           		Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom,
					           	};
					list.CheckedListBox.Items.AddRange(reader.ReadAll().ToArray());
					offset += list.Width + 10;
					panel.Controls.Add(list);
					pattern.Text = Settings.Default.pattern;
					footer.Text = Settings.Default.footer;
					header.Text = Settings.Default.header;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void BuildBody(List<StorageItem[]> items, Stack<StorageItem> already, StringBuilder builder)
		{

			if (already.Count == items.Count)
				builder.Append(
					string.Format(pattern.Text, already.Reverse().Select(si => si.Key).ToArray() as object[])
					).Append("\n");
			else
			{
				var myLevel = items[already.Count];
				foreach(var item in myLevel)
				{
					already.Push(item);
					BuildBody(items, already, builder);
					already.Pop();
				}
			}
		}

		private string BuildResult()
		{
			var lists = new List<StorageItem[]>();
			var response = new StringBuilder(header.Text).Append("\r\n");
			for (var i = 0; i < panel.Controls.Count; i++)
			{
				if (panel.Controls[i] is CustomCheckedListBox)
					lists.Add(
						(panel.Controls[i] as CustomCheckedListBox)
						.CheckedListBox
						.CheckedItems
						.Cast<StorageItem>().ToArray());
			}
			var bodyBuilder = new StringBuilder();
			BuildBody(lists, new Stack<StorageItem>(lists.Count), bodyBuilder);
			response.Append(bodyBuilder.ToString()).Append("\r\n");
			response.Append(footer.Text);
			return response.ToString();
		}

		private void button_Click(object sender, EventArgs e)
		{
			try
			{
				var result = BuildResult();
				var fi = new FileInfo(Settings.Default.result);
				if (!Directory.Exists(fi.DirectoryName))
					Directory.CreateDirectory(fi.DirectoryName);
				File.WriteAllText(fi.FullName, result);
				Process.Start("notepad", fi.FullName);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void buttonBR_Click(object sender, EventArgs e)
		{
			try
			{
				var result = BuildResult();
				var fi = new FileInfo(Settings.Default.result);
				if (!Directory.Exists(fi.DirectoryName))
					Directory.CreateDirectory(fi.DirectoryName);
				File.WriteAllText(fi.FullName, result);
				Process.Start(fi.FullName);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
	}
}
